package com.common.common;

import com.common.exception.ErrCode;
import com.common.exception.SeException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.noear.solon.annotation.Component;
import org.noear.solon.cloud.utils.http.HttpUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName Request
 * @Description 请求封装
 * @Version 1.0
 **/
@Component
@SuppressWarnings("CallToPrintStackTrace")
public class Request {

    /**
     * get请求
     *
     * @param url url
     * @return 返回body
     */
    public String get(String url) {
        try {
            // 这里返回的是 json str，直接fast json到对象即可
            return HttpUtils.http(url).headers(headers()).get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new SeException(ErrCode.System_Error);
        }
    }

    /**
     * post请求
     *
     * @param url  url
     * @param body 请求body
     * @return 返回body
     */
    public String post(String url, Object body) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String req = mapper.writeValueAsString(body);
            // 这里返回的是 json str，直接fast json到对象即可
            return HttpUtils.http(url).bodyJson(req).headers(headers()).post();
        } catch (Exception e) {
            e.printStackTrace();
            throw new SeException(ErrCode.System_Error);
        }
    }

    /**
     * 设置basic加密
     *
     * @return header
     */
    private Map<String, String> headers() {
        return new HashMap<>(){{
            put("Content-Type", "application/json;charset=UTF-8");
            // ...
        }};
    }
}
